const {
  serviceId, bindPassword, cubeSendUuidNotify,
  cubeReceiveUuidWrite, parseRes, writeBLECharacteristicValue,
  reply, bluetoothAdapterState,closeCube,
  discovery, parseAdvertisData,closeBLEConnection
} = require('../../utils/bluetooth');
const {
  ab2hex, alert, array2arrayBuffer, json2string,
  digit2hex, getSeqNum, isIOS, log,
  jump, query2obj, obj2query,
  objValues, getCubeName, goToDeviceInfo,findMatchedDevices,cubeIsOnline,pageDeltaInStack,matchedDevicesHandler
} = require('../../utils/util');

const app = getApp();
const _ = require('../../utils/underscore');

Page({
  data: {
    devices: [],
    startX: 0,
    delBtnWidth: 96 //rpx
  },
  onLoad: function (options) {
    const delta = pageDeltaInStack('deviceInfo');
    if (delta<=0) {
      const serialNumber = wx.getStorageSync('lastCubeSerialNumber');
      //const cubeName = wx.getStorageSync('lastCubeName');
      const cubeName = getCubeName({serialNumber});
      try {
        if (serialNumber) {
          const online = cubeIsOnline();
          goToDeviceInfo({serialNumber,needConnect:online?0:1});
        }
      } catch (e) {
        log('devices page catch error');
      }
    }
  // todo 处理设备离线（不重连）
  },
  onUnload: function () {
  },
  onHide: function () {
  },
  onShow: function () {
    const devices = findMatchedDevices();
    log(`devices page, devices=${JSON.stringify(devices)}`);
    this.setData({devices});
  },
  scanCode: function () {

    // app.globalData.ignoreAppOnHide = false;

    setTimeout(function () {
      // 允许从相机和相册扫码
      wx.scanCode({
        onlyFromCamera: true,
        success: function (res) {

          const {result, scanType, charSet, path} = res;
          const {id} = query2obj(result);
          if(id){
            jump({pageName: 'searchBySerialNumber', params: {id}, type: 1});
          }else{
            jump({pageName:'scanIncorrectCode',type:1});
          }
        },
        fail: function () {

        }
      })
    },300);

  },
  bluetooth: function () {
    // return cubeOnOffHandler2();
    const that = this;
    bluetoothAdapterState({
      success: function () {
        jump({pageName: 'scaning', type: 1});
      },
      fail: function () {
        wx.showToast({title: '请打开蓝牙', icon: 'none'});
      }
    });

  },
  tapDevice: function (e) {
    const that = this;

    let {device} = e.currentTarget.dataset;
    device = 'string' === typeof device ? JSON.parse(device) : device;
    const {serialNumber, cubeName} = device;

    log(`serialNumber taped is:${serialNumber}, cubeName is: ${cubeName}`);

    const lastCubeSerialNumber = wx.getStorageSync('lastCubeSerialNumber');
    const online = cubeIsOnline();
    if(lastCubeSerialNumber+'' === serialNumber+''){
      let needConnect = online?0:1;
      goToDeviceInfo({serialNumber,needConnect});
    }else{
      if(online){
        closeCube(function (){
          goToDeviceInfo({serialNumber,needConnect:1});
        });
      }else{
        goToDeviceInfo({serialNumber,needConnect:1});
      }
    }
  },
  //手指刚放到屏幕触发
  touchS: function (e) {
    log("touchS" + e);
    //判断是否只有一个触摸点
    if (e.touches.length === 1) {
      const {devices} = this.data;
      const {index} = e.currentTarget.dataset;
      this.setData({
        //记录触摸起始位置的X坐标
        startX: e.touches[0].clientX,
        devices: devices.map(d => {
          d.txtStyle = 'left:0';
          return d;
        })
      });
    }
  },
  //触摸时触发，手指在屏幕上每移动一次，触发一次
  touchM: function (e) {
    log("touchM:" + e);
    const that = this;
    if (e.touches.length === 1) {
      //记录触摸点位置的X坐标
      const moveX = e.touches[0].clientX;
      //计算手指起始点的X坐标与当前触摸点的X坐标的差值
      const disX = that.data.startX - moveX;
      //delBtnWidth 为右侧按钮区域的宽度
      const delBtnWidth = that.data.delBtnWidth;
      let txtStyle = "";
      if (disX <= 0) {//如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0";
      } else {//移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "rpx";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "rpx";
        }
      }
      //获取手指触摸的是哪一个item
      const {index} = e.currentTarget.dataset;
      let {devices} = that.data;
      //将拼接好的样式设置到当前item中
      devices[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({devices});
    }
  },
  touchE: function (e) {
    log("touchE" + e);
    const that = this;
    if (e.changedTouches.length === 1) {
      //手指移动结束后触摸点位置的X坐标
      const endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      const disX = that.data.startX - endX;
      const {delBtnWidth} = that.data;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      const txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0";
      //获取手指触摸的是哪一项
      const {index} = e.currentTarget.dataset;
      let {devices} = that.data;
      devices[index].txtStyle = txtStyle;
      //更新列表的状态
      that.setData({devices});
    }
  },
  delDevice: function (e) {
    const {index} = e.currentTarget.dataset;
    let {devices} = this.data,
      deviceId,
      lastSerialNumber;
    const serialNumber = devices[index].serialNumber + '';
    devices = devices.filter((v, i) => i !== index);
    this.setData({devices});

    try {
      lastSerialNumber = wx.getStorageSync('lastCubeSerialNumber') + '';
      if (lastSerialNumber && lastSerialNumber === serialNumber) {
        wx.removeStorageSync('lastCubeSerialNumber');
        //wx.removeStorageSync('lastCubeName');
      }
    } catch (e) {

    }

    try{
      matchedDevicesHandler({serialNumber,action:'delete'});
    }catch (e) {

    }

    try {
      deviceId = JSON.parse(wx.getStorageSync(serialNumber)).deviceId;//cube重启后会变
      wx.removeStorageSync(serialNumber);
    } catch (e) {
      deviceId = '';
    }

    if (deviceId) {
      closeBLEConnection({
        deviceId, complete: function () {
          if (findMatchedDevices().length === 0 || (lastSerialNumber && lastSerialNumber === serialNumber && getCurrentPages().length > 1)) {
            wx.reLaunch({
              url: '/pages/devices/devices'
            })
          }
        }
      });
    }
  }
});
